package com.gestordeavisos;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class DatosXMLServlet extends HttpServlet {
	
	 
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		
		
		resp.setContentType("text/xml");
		PrintWriter pw = resp.getWriter();
		//pw.println("<?xml version='1.0' encoding='utf-8'?>");
		UserService userService = UserServiceFactory.getUserService();
	    User user = userService.getCurrentUser();
	    if (user == null) {
	    	pw.println("<avisos><error>Error usuario</error></avisos>");
	    }
	    else
	    {
	    	PersistenceManager pm = PMF.get().getPersistenceManager();
	    	String select_query = "select from " + Aviso.class.getName(); 
			Query query = pm.newQuery(select_query); 
			query.setFilter("autor == paramAutor"); 
			query.declareParameters("java.lang.String paramAutor"); 
			List<Aviso> avisos = (List<Aviso>) query.execute(user);
			if (avisos.isEmpty()) {
				pw.println("<avisos><error>No hay avisos</error></avisos>");
			}
			else
			{
				pw.println("<?xml version='1.0' encoding='utf-8' ?>");
				pw.println("<avisos>");
				for(Aviso a : avisos)
				{			
					pw.println("<aviso>" +
							"<actividad>"+a.getActividad()+"</actividad>" +
							"<cuanto>"+a.getCuanto()+"</cuanto>");
					for(int i=0; i<a.getCuando().size();i++)
					{
						pw.println("<cuando>"+a.getCuando().get(i)+"</cuando>");
					}
					pw.println("<autor>"+a.getAutor()+"</autor>" +
					"<fecha>"+a.getFecha()+"</fecha>" +
					"<repeticion>"+a.getRepeticion()+"</repeticion>"+
					"</aviso>");
				}
				pw.println("</avisos>");
			}
			
			pm.close();
		  }
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
		
	}

}
